import Vue from 'vue';
import Vuex from 'vuex';
import { setToken } from '../utils/auth';

import {
  loginSuccess,
  showLogin,
  showRegist,
  logout
} from './login';
import { login, register } from '../request/api';

Vue.use(Vuex);

const eventBus = new Vue();

export default new Vuex.Store({
  state: {
    userId: '1',
    showLogin: false,
    userInfo: null,
    reload: true,
    eventBus
  },
  mutations: {
    LOGIN_SUCCESS: loginSuccess,
    SHOW_LOGIN: showLogin,
    SHOW_REGIST: showRegist,
    LOGOUT: logout,
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_RELOAD: (state, reload) => {
      state.reload = reload;
    }
  },
  actions: {
    login({ commit }, params) {
      return new Promise((resolve, reject) => {
        login(params).then(data => {
          data.userinfo = {
            id: 1,
            name: '测试',
            balance: 10,
            freeze_money: 100,
            account: '18665432710'
          };
          commit('SET_TOKEN', data.token);
          commit('SHOW_LOGIN', false);
          commit('LOGIN_SUCCESS', data.userinfo);
          setToken(data.token);
          resolve(data);
        }).catch(res => {
          reject(res);
        });
      });
    },
    regist({ commit }, params) {
      return new Promise((resolve, reject) => {
        register(params).then(data => {
          commit('SHOW_LOGIN', true);
          resolve(data.data);
        }).catch(res => {
          reject(res);
        });
      });
    }
  },
  modules: {
  },
});
